use std::sync::Arc;
use anyhow::Result;
use async_nats::jetstream;
use async_nats::jetstream::consumer::DeliverPolicy;
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use tracing::{info, error, warn};

use crate::service::ReservationService;

#[derive(Debug, Serialize, Deserialize)]
pub struct ReservationEvent {
    pub event_type: EventType,
    pub reservation_id: Option<i32>,
    pub reservation_data: Option<NewReservationData>,
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum EventType {
    NewReservation,
    PaymentCompleted,
    PaymentFailed,
    CheckIn,
    CheckOut,
    Cancelled,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct NewReservationData {
    pub guest_name: String,
    pub guest_email: String,
    pub guest_phone: String,
    pub room_number: String,
    pub check_in_date: String,
    pub check_out_date: String,
    pub total_amount: f64,
}

pub struct NatsHandler {
    service: Arc<ReservationService>,
    nats_url: String,
}

impl NatsHandler {
    pub fn new(service: Arc<ReservationService>, nats_url: String) -> Self {
        Self { service, nats_url }
    }

    pub async fn start(&self) -> Result<()> {
        let client = async_nats::connect(&self.nats_url).await?;
        let jetstream = jetstream::new(client);

        // 创建stream
        let stream = jetstream
            .get_or_create_stream(jetstream::stream::Config {
                name: "hotel_reservations".to_string(),
                subjects: vec![
                    "reservation.new".to_string(),
                    "reservation.payment.completed".to_string(),
                    "reservation.payment.failed".to_string(),
                    "reservation.checkin".to_string(),
                    "reservation.checkout".to_string(),
                    "reservation.cancelled".to_string(),
                ],
                ..Default::default()
            })
            .await?;

        // 创建消费者
        let consumer = stream
            .get_or_create_consumer(
                "reservation_processor",
                jetstream::consumer::pull::Config {
                    deliver_policy: DeliverPolicy::All,
                    ..Default::default()
                },
            )
            .await?;

        info!("Starting NATS message processor...");

        let mut messages = consumer.messages().await?;

        while let Some(message) = messages.next().await {
            match message {
                Ok(msg) => {
                    info!("📨 收到新的NATS消息");
                    if let Err(e) = self.process_message(&msg).await {
                        error!("❌ 处理消息失败: {}", e);
                        error!("失败消息内容: {}", String::from_utf8_lossy(&msg.payload));
                    } else {
                        info!("✅ 消息处理成功");
                    }
                    if let Err(e) = msg.ack().await {
                        error!("❌ 消息确认失败: {}", e);
                    } else {
                        info!("✅ 消息已确认");
                    }
                }
                Err(e) => {
                    error!("❌ 接收消息错误: {}", e);
                }
            }
        }

        info!("=== 消息处理完成 ===");
        Ok(())
    }

    async fn process_message(&self, message: &async_nats::jetstream::Message) -> Result<()> {
        let payload = String::from_utf8_lossy(&message.payload);
        
        info!("=== NATS消息收到 ===");
         info!("主题: {}", message.subject);
         info!("回复地址: {}", message.reply.as_deref().unwrap_or("无"));
         info!("消息内容: {}", payload);

        let event: ReservationEvent = serde_json::from_str(&payload)?;
        info!("事件类型: {:?}", event.event_type);
        info!("时间戳: {}", event.timestamp);
        
        if let Some(reservation_id) = event.reservation_id {
            info!("预订ID: {}", reservation_id);
        }

        match event.event_type {
            EventType::NewReservation => {
                info!("开始处理新建预订事件");
                if let Some(data) = event.reservation_data {
                    info!("预订数据: 客人={}, 邮箱={}, 房间={}, 入住={}, 退房={}, 金额={}", 
                          data.guest_name, data.guest_email, data.room_number, 
                          data.check_in_date, data.check_out_date, data.total_amount);
                    
                    let check_in_date = chrono::NaiveDate::parse_from_str(&data.check_in_date, "%Y-%m-%d")?;
                    let check_out_date = chrono::NaiveDate::parse_from_str(&data.check_out_date, "%Y-%m-%d")?;

                    let reservation = self.service.create_reservation(
                        data.guest_name,
                        data.guest_email,
                        data.guest_phone,
                        data.room_number,
                        check_in_date,
                        check_out_date,
                        data.total_amount,
                    ).await?;

                    info!("✅ 成功创建预订: ID={}, 客人={}, 房间={}", 
                          reservation.id, reservation.guest_name, reservation.room_number);
                } else {
                    warn!("❌ 新建预订事件缺少预订数据");
                }
            }
            EventType::PaymentCompleted => {
                info!("开始处理支付完成事件");
                if let Some(id) = event.reservation_id {
                    info!("正在更新预订状态为已付款: ID={}", id);
                    if let Some(reservation) = self.service
                        .update_reservation_status(id, crate::grpc::reservation::ReservationStatus::Paid)
                        .await? {
                        info!("✅ 成功更新预订状态: ID={}, 新状态=PAID", reservation.id);
                    } else {
                        warn!("❌ 未找到预订ID: {}", id);
                    }
                } else {
                    warn!("❌ 支付完成事件缺少预订ID");
                }
            }
            EventType::CheckIn => {
                info!("开始处理入住事件");
                if let Some(id) = event.reservation_id {
                    info!("正在更新预订状态为已入住: ID={}", id);
                    if let Some(reservation) = self.service
                        .update_reservation_status(id, crate::grpc::reservation::ReservationStatus::CheckedIn)
                        .await? {
                        info!("✅ 成功更新预订状态: ID={}, 新状态=CHECKED_IN", reservation.id);
                    } else {
                        warn!("❌ 未找到预订ID: {}", id);
                    }
                } else {
                    warn!("❌ 入住事件缺少预订ID");
                }
            }
            EventType::CheckOut => {
                info!("开始处理退房事件");
                if let Some(id) = event.reservation_id {
                    info!("正在更新预订状态为已退房: ID={}", id);
                    if let Some(reservation) = self.service
                        .update_reservation_status(id, crate::grpc::reservation::ReservationStatus::CheckedOut)
                        .await? {
                        info!("✅ 成功更新预订状态: ID={}, 新状态=CHECKED_OUT", reservation.id);
                    } else {
                        warn!("❌ 未找到预订ID: {}", id);
                    }
                } else {
                    warn!("❌ 退房事件缺少预订ID");
                }
            }
            EventType::Cancelled => {
                info!("开始处理取消预订事件");
                if let Some(id) = event.reservation_id {
                    info!("正在取消预订: ID={}", id);
                    if let Some(reservation) = self.service
                        .cancel_reservation(id, "Cancelled via NATS".to_string())
                        .await? {
                        info!("✅ 成功取消预订: ID={}, 状态=CANCELLED", reservation.id);
                    } else {
                        warn!("❌ 未找到预订ID: {}", id);
                    }
                } else {
                    warn!("❌ 取消事件缺少预订ID");
                }
            }
            EventType::PaymentFailed => {
                warn!("⚠️ 支付失败事件: 预订ID={:?}, 时间={}", event.reservation_id, event.timestamp);
                // 在实际应用中，这里可以发送通知或执行其他业务逻辑
            }
        }

        Ok(())
    }
}